package com.test.weixin.web;

import com.alibaba.fastjson.JSON;
import com.test.weixin.constant.WxConstant;
import com.test.weixin.util.WxSignUtil;
import com.test.weixin.util.WxXmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.SortedMap;

/**
 * Created by Administrator on 2019/2/14.
 * 支付结果通知  https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
 */
@RestController
@RequestMapping("/callbackApi")
public class PayCallbackApi {
    private static final Logger logger = LoggerFactory.getLogger(PayCallbackApi.class);
    /**
     * 微信统一下单  回调地址
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/pay/weixin", method = RequestMethod.POST)
    public void wexinNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlData = "";
//
//            InputStream inStream = request.getInputStream();
//            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
//            byte[] buffer = new byte[1024];
//            int len = 0;
//            while ((len = inStream.read(buffer)) != -1) {
//                outSteam.write(buffer, 0, len);
//            }
//            outSteam.close();
//            inStream.close();
//            xmlData = new String(outSteam.toByteArray(), "utf-8");

            String inputLine;
            try {
                while ((inputLine = request.getReader().readLine()) != null) {
                    xmlData += inputLine;
                }
                request.getReader().close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            SortedMap<String, String> resultMap = WxXmlUtil.xmlStrToMap(xmlData);
            logger.info("微信支付回调数据=requst:{}", JSON.toJSON((resultMap)) );
            //签名验证
            String newSign = WxSignUtil.createSign( resultMap);
            String oldSign = resultMap.get("sign");//签名
            logger.warn("验证= signStr:{},sign:{}", newSign, oldSign);
            if (newSign.equals(oldSign)) {
                // 签名 认证成功  判断结果
                String result_code = resultMap.get("result_code");//业务结果
                if (result_code.equals(WxConstant.SUCCESS)) {

                    logger.info("支付成功= 订单号:{},微信交易号:{}", resultMap.get("out_trade_no"),  resultMap.get("transaction_id"));
                    //TODO  需 校验返回的订单金额是否与商户订单金额一致  处理支付成功业务逻辑
                    //

                }
                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                out.write(WxXmlUtil.notifyXmlBytes());
                out.flush();
                out.close();
            }else{
                logger.warn("微信支付回调地址请求参数签名验证失败= newSign:{},oldSign:{}", newSign, oldSign);
            }
        } catch (Exception ex) {
            logger.warn("微信支付回调地址处理异常:{}", ex);
            ex.printStackTrace();
        }
    }
}
